package com.gmrz.uaf.protocol.v1.validaton.auth;

import com.gmrz.uaf.protocol.v1.processor.exception.UAFErrorCode;
import com.gmrz.uaf.protocol.v1.schema.*;
import com.gmrz.uaf.protocol.v1.validaton.Validator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class AuthSignAssertionValidator implements
		Validator<AuthenticationAssertion> {
	private static final Logger LOG = LogManager
			.getLogger(AuthSignAssertionValidator.class);
	private Authenticator authntr;
	private String fcpBase64;
	private ServerData serverData;

	public AuthSignAssertionValidator(Authenticator authntr, String fcpBase64,
			ServerData serverData) {
		this.authntr = authntr;
		this.fcpBase64 = fcpBase64;
		this.serverData = serverData;
	}

	public void validate(AuthenticationAssertion assertion)
			throws AuthSignAssertionValidationException {
		String msg = "";

//		int aStatus = this.authntr.getStatus();
//		if (aStatus != Constants.AuthenticatorStatus.ACTIVE.getStatus()) {
//			msg = "Authenticator [" + this.authntr.getAAID() + "] is ["
//					+ aStatus + "]";
//			logAndThrowASAVE(msg,
//					UAFErrorCode.STATUS_AUTHENTICATOR_STATE_INVALID);
//		}
//		String username = this.serverData.getUserName();
//		if ((!Strings.isNullOrEmpty(username))
//				&& (!username.equalsIgnoreCase(this.authntr.getUserName()))) {
//			msg = "Authenticator username[" + this.authntr.getUserName()
//					+ "] doesn't matches with username[" + username
//					+ "] in ServerData";
//			logAndThrowASAVE(msg,
//					UAFErrorCode.PROTOCOL_SERVERDATA_VALIDATION_FAILED);
//		}
        // 获取响应断言中的方案
		String signDataScheme = assertion.getSignDataScheme();
		// 获取已注册的认证数据中的元数据中的断言方案
		String expectedAssertionScheme = this.authntr.getMetadata()
				.getAssertionScheme();
		if ((signDataScheme == null)
				|| (!signDataScheme.equals(expectedAssertionScheme))) {
			msg = "Auth sign assertion scheme[" + signDataScheme
					+ "] doesn't macthes with metadata["
					+ expectedAssertionScheme + "]";
			logAndThrowASAVE(msg, UAFErrorCode.PROTOCOL_ASSERTION_SCHEME_INVALID);
		}
        // 从认证断言中获取的 签名响应
		ASMSignResponse signResponse = assertion.getSignResponse();
		if (signResponse == null) {
			msg = "Authenticator signed response is missing, rejecting the Auth response";
			logAndThrowASAVE(msg, UAFErrorCode.PROTOCOL_SIGNDATA_VALIDATION_FAILED);
		}

		SignData signData = signResponse.getSignData();
		ASMSignDataValidator sdv = new ASMSignDataValidator(this.authntr,
				this.fcpBase64, this.serverData);
		// signData数据的校验
		sdv.validate(signData);
	}

	void logAndThrowASAVE(String msg, UAFErrorCode ec)
			throws AuthSignAssertionValidationException {
		LOG.error(msg);
		throw new AuthSignAssertionValidationException(ec);
	}
}
